{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ad1bbec",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from agents import Agent, Runner, trace, Tool\n",
    "from agents.mcp import MCPServerStdio\n",
    "from IPython.display import Markdown, display\n",
    "from datetime import datetime\n",
    "import asyncio, traceback\n",
    "\n",
    "os.environ[\"PATH\"] = \"/home/sngo/.nvm/versions/node/v22.20.0/bin:/home/sngo/.local/bin:\" + os.environ[\"PATH\"]\n",
    "load_dotenv(override=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ac8c667",
   "metadata": {},
   "source": [
    "## Test the complete BDD agent with all 3 MCP servers:\n",
    "1. Playwright \n",
    "2. Assertion\n",
    "4. Filesystem "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c6932a5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup\n",
    "current_dir = os.getcwd()\n",
    "test_results_dir = os.path.join(current_dir, \"test-results\")\n",
    "reports_dir = os.path.join(test_results_dir, \"reports\")\n",
    "screenshots_dir = os.path.join(test_results_dir, \"screenshots\")\n",
    "\n",
    "os.makedirs(reports_dir, exist_ok=True)\n",
    "os.makedirs(screenshots_dir, exist_ok=True)\n",
    "    \n",
    "print(\"🚀 Starting Full BDD Agent Test\")\n",
    "print(f\"📁 Test results: {test_results_dir}\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cc7cd8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Gherkin feature to test\n",
    "gherkin_feature = \"\"\"\n",
    "Feature: Todo App Management\n",
    "  As a user\n",
    "  I want to manage my todo items\n",
    "  So that I can track my tasks\n",
    "\n",
    "  Scenario: Add a new todo item\n",
    "    Given I navigate to \"https://eviltester.github.io/simpletodolist/todo.html\"\n",
    "    When I type the input field \"Enter new todo text here\" with text \"Buy groceries\" - hint: use browser_type tool\n",
    "    And I press the \"Enter\" key\n",
    "    Then I should see text \"Buy groceries\" on the page\n",
    "    And the todo list should contain at least 1 item\n",
    "\n",
    "  Scenario: Add multiple todos\n",
    "    Given I navigate to \"https://eviltester.github.io/simpletodolist/todo.html\"\n",
    "    When I add todo \"First task\"\n",
    "    And I add todo \"Second task\"\n",
    "    Then I should see text \"First task\" on the page\n",
    "    And I should see text \"Second task\" on the page\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "916ef9da",
   "metadata": {},
   "outputs": [],
   "source": [
    "# System prompt for the agent\n",
    "system_prompt = f\"\"\"You are an expert BDD testing engineer with MEMORY of previous scenarios.\n",
    "\n",
    "## Available Tools:\n",
    "1. **Browser Automation** (Playwright): browser_navigate, browser_fill_form, browser_press_key, browser_take_screenshot, browser_snapshot, browser_click\n",
    "2. **Assertions**: assert_equals, assert_contains, assert_not_contains, assert_count, assert_greater_than\n",
    "3. **Filesystem**: write_file, read_file, list_directory\n",
    "\n",
    "## Your Task:\n",
    "Execute the provided Gherkin feature file scenario by scenario, maintaining context across all scenarios.\n",
    "\n",
    "## Context Memory Rules:\n",
    "1. **Learn Once, Apply Many**: When you figure out how to do something (e.g., \"add a todo\"), remember the exact steps\n",
    "2. **Pattern Matching**: Recognize when new steps match patterns you've already learned\n",
    "3. **Incremental Knowledge**: Each scenario adds to your understanding of the application\n",
    "4. **Don't Repeat Discovery**: If you learned \"add todo\" means \"type input + press Enter\", don't rediscover it\n",
    "\n",
    "## Concrete Example:\n",
    "```gherkin\n",
    "Scenario 1: Add a new todo item\n",
    "  When I type the input field \"Enter new todo text here\" with text \"Buy groceries\"\n",
    "  And I press the \"Enter\" key\n",
    "  # You learn: \"add todo\" = specific selectors and actions\n",
    "\n",
    "Scenario 2: Add multiple todos  \n",
    "  When I add todo \"First task\"\n",
    "  # You apply: Use the pattern from Scenario 1 automatically\n",
    "  # You know: type the input field \"Enter new todo text here\" with text + press \"Enter\"\n",
    "```\n",
    "\n",
    "## Execution Standards:\n",
    "- Take screenshots: start of scenario, before actions, after assertions\n",
    "- Save final report to: {reports_dir}\n",
    "- One comprehensive JSON report covering ALL scenarios\n",
    "- Reuse learned patterns for efficiency\n",
    "- Pause for 20 seconds between each scenario.\n",
    "\n",
    "Execute with intelligence and memory across all scenarios.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dccf3be1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7e18aac",
   "metadata": {},
   "outputs": [],
   "source": [
    "# parameters\n",
    "mcp_server_params = [\n",
    "    {\"command\":\"npx\", \"args\":[\"@playwright/mcp@latest\", \"--browser\", \"chromium\", \"--headless\", \"--isolated\"]},\n",
    "    {\"command\":\"python\", \"args\":[\"mcp-servers/assertion-server/assertion_server_python.py\"]},\n",
    "    {\"command\":\"npx\", \"args\":[\"-y\", \"@modelcontextprotocol/server-filesystem\", test_results_dir]}\n",
    "]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a37e8bfc",
   "metadata": {},
   "outputs": [],
   "source": [
    "temp_param =  {\"command\":\"python\", \"args\":[\"mcp-servers/assertion-server/assertion_server_python.py\"]}\n",
    "server = MCPServerStdio(temp_param, client_session_timeout_seconds=600)\n",
    "try:\n",
    "    await server.connect()\n",
    "    print(f\"✅ Connected: {temp_param['args']}\")\n",
    "except Exception as e:\n",
    "    print(f\"❌ Error connecting to {temp_param['command']}: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d1461ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "# mcp_servers = [MCPServerStdio(params, client_session_timeout_seconds=600) for params in mcp_server_params]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e3245fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# BDD Agent\n",
    "async def getBddAgent(mcp_servers) -> Agent:\n",
    "    bddAgent = Agent(\n",
    "        name = \"BddAgent\",\n",
    "        instructions=system_prompt,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        mcp_servers=mcp_servers\n",
    "    )\n",
    "\n",
    "    return bddAgent;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd41d8c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "mcp_servers = []\n",
    "for i, params in enumerate(mcp_server_params):\n",
    "    try:\n",
    "        print(f\"\\nTesting server {i+1}: {params['args']}\")\n",
    "        server = MCPServerStdio(params, client_session_timeout_seconds=600)\n",
    "        await server.connect()\n",
    "        mcp_servers.append(server)\n",
    "        await asyncio.sleep(3.0)\n",
    "        await asyncio.sleep(0)\n",
    "        print(\"Connected OK!\")\n",
    "    except Exception as e:\n",
    "        print(f\"❌ Error connecting to {params['args']}: {e}\")\n",
    "        traceback.print_exc()\n",
    "        await asyncio.sleep(2.0)\n",
    "\n",
    "bddAgent = await getBddAgent(mcp_servers)\n",
    "with trace(\"Bdd\"):\n",
    "    await Runner.run(bddAgent, gherkin_feature, max_turns=60)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "013ee65c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
